package design_pattern.study.spring;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/***
 *
 * @author fb_li
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader{

    private BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        this.registry = new SimpleBeanDefinitionRegistry();
    }
    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    /**
     * 使用dom4解析XML文件
     * @param configLocation
     * @throws Exception
     */
    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {

        InputStream is = this.getClass().getClassLoader().getResourceAsStream(configLocation);
        SAXReader reader = new SAXReader();//
        Document document = reader.read(is);//读取输入流 为Document对象
        Element rootElement = document.getRootElement();//获取根元素 beans
        //解析bean标签
        parseBean(rootElement);
    }

    private void parseBean(Element rootElement) {

        List<Element> elements = rootElement.elements("bean");//获取所有bean子标签
        for (Element element : elements) {
            String id = element.attributeValue("id");//获取对应属性
            String className = element.attributeValue("class");
            BeanDefinition beanDefinition = new BeanDefinition();//封装BeanDefinition
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);
            List<Element> list = element.elements("property");//获取所有property子标签
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            for (Element element1 : list) {
                String name = element1.attributeValue("name");
                String ref = element1.attributeValue("ref");
                String value = element1.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name,ref,value);
                mutablePropertyValues.addPropertyValue(propertyValue);
            }
            beanDefinition.setMutablePropertyValues(mutablePropertyValues);

            registry.registerBeanDefinition(id,beanDefinition);//注册到Map集合容器中
        }
    }
}
